const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors');
const multer = require('@koa/multer');
const fs = require('fs');
const path = require('path');
const pool = require('./db');

const app = new Koa();
const router = new Router();

// 全局错误处理
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        console.error('服务器错误:', err);
        ctx.status = err.status || 500;
        ctx.body = {
            success: false,
            message: err.message || '服务器内部错误',
            error: err.toString()
        };
    }
});

// 请求日志中间件
app.use(async (ctx, next) => {
    const start = Date.now();
    console.log(`📨 ${ctx.method} ${ctx.url}`);
    await next();
    const ms = Date.now() - start;
    console.log(`📤 ${ctx.method} ${ctx.url} - ${ctx.status} (${ms}ms)`);
});

// 中间件配置
app.use(cors());
app.use(bodyParser());

// 配置文件上传
const upload = multer({
    dest: path.join(__dirname, 'uploads/'),
    limits: {
        fileSize: 50 * 1024 * 1024 // 50MB
    }
});

// 健康检查
router.get('/health', async (ctx) => {
    console.log('健康检查被调用');
    ctx.body = { 
        status: 'ok', 
        message: '音乐服务器运行正常',
        timestamp: new Date().toISOString()
    };
});

// 获取所有歌曲 - 直接在此文件中实现
router.get('/api/songs', async (ctx) => {
    console.log('获取歌曲列表被调用');
    try {
        const [songs] = await pool.execute('SELECT * FROM songs ORDER BY id DESC');
        console.log(`找到${songs.length}首歌曲`);
        ctx.body = {
            success: true,
            data: songs
        };
    } catch (error) {
        console.error('获取歌曲列表失败:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取歌曲列表失败: ' + error.message
        };
    }
});

// 添加歌曲
router.post('/api/songs', async (ctx) => {
    console.log('添加歌曲被调用，请求体:', ctx.request.body);
    try {
        const { name, artist } = ctx.request.body;
        
        if (!name) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '歌名不能为空'
            };
            return;
        }
        
        // 检查是否已存在相同歌名
        const [existingSong] = await pool.execute('SELECT * FROM songs WHERE title = ?', [name]);
        if (existingSong.length > 0) {
            ctx.status = 409;
            ctx.body = {
                success: false,
                message: '歌名已存在'
            };
            return;
        }
        
        // 添加歌曲，artist 支持前端传入，否则默认“未知歌手”
        const finalArtist = artist && String(artist).trim() ? artist : '未知歌手';
        const [result] = await pool.execute(
            'INSERT INTO songs (title, artist, song_url) VALUES (?, ?, ?)', 
            [name, finalArtist, 'http://localhost:3000/placeholder']
        );
        
        ctx.body = {
            success: true,
            data: {
                id: result.insertId,
                title: name,
                artist: finalArtist
            },
            message: '歌曲添加成功'
        };
        
        console.log('歌曲添加成功:', { id: result.insertId, name, artist: finalArtist });
        
    } catch (error) {
        console.error('添加歌曲失败:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '添加歌曲失败: ' + error.message
        };
    }
});

// 获取所有歌手
router.get('/api/songers', async (ctx) => {
    console.log('获取歌手列表被调用');
    try {
        const [songers] = await pool.execute('SELECT * FROM songers ORDER BY id DESC');
        console.log(`找到${songers.length}位歌手`);
        ctx.body = {
            success: true,
            data: songers
        };
    } catch (error) {
        console.error('获取歌手列表失败:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '获取歌手列表失败: ' + error.message
        };
    }
});

// 添加歌手
router.post('/api/songers', async (ctx) => {
    console.log('添加歌手被调用，请求体:', ctx.request.body);
    try {
        const { name } = ctx.request.body;
        
        if (!name) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '歌手名不能为空'
            };
            return;
        }
        
        // 检查是否已存在相同歌手名
        const [existingSinger] = await pool.execute('SELECT * FROM songers WHERE name = ?', [name]);
        if (existingSinger.length > 0) {
            ctx.status = 409;
            ctx.body = {
                success: false,
                message: '歌手名已存在'
            };
            return;
        }
        
        const [result] = await pool.execute('INSERT INTO songers (name) VALUES (?)', [name]);
        
        ctx.body = {
            success: true,
            data: {
                id: result.insertId,
                name: name
            },
            message: '歌手添加成功'
        };
        
        console.log('歌手添加成功:', { id: result.insertId, name });
        
    } catch (error) {
        console.error('添加歌手失败:', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '添加歌手失败: ' + error.message
        };
    }
});

// 根路由
router.get('/', async (ctx) => {
    ctx.body = { 
        message: '🎵 音乐管理系统调试服务器', 
        version: '2.0.0'
    };
});

// 使用路由
app.use(router.routes());
app.use(router.allowedMethods());

// 启动服务器
const PORT = 3001; // 使用不同端口避免冲突
const HOST = '0.0.0.0';

app.listen(PORT, HOST, () => {
    console.log('\n🔧 调试服务器已启动');
    console.log('=====================================');
    console.log(`📡 地址: http://localhost:${PORT}`);
    console.log('🚀 可用接口:');
    console.log(`   - 健康检查: GET http://localhost:${PORT}/health`);
    console.log(`   - 歌曲管理: GET/POST http://localhost:${PORT}/api/songs`);
    console.log(`   - 歌手管理: GET/POST http://localhost:${PORT}/api/songers`);
    console.log('=====================================');
    console.log('✅ 调试服务器就绪！');
});

// 优雅关闭处理
process.on('SIGINT', () => {
    console.log('\n🛑 关闭调试服务器...');
    process.exit(0);
});